package com.xiehua.task.persistence.rocks;

import com.xiehua.task.job.pool.DelayJob;
import com.xiehua.task.job.pool.Job;
import com.xiehua.task.prop.XiehuaConfig;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.rocksdb.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.xiehua.task.prop.XiehuaConfig.PERSISTENCE_PATH;


/***
 * api保留，但不建议使用
 * @see  RocksPool
 * **/
@Deprecated
public class RocksUtils {

    private RocksDB rocksDB;

    static {
        RocksDB.loadLibrary();
    }

    public void put(String key,String value) throws RocksDBException {
        Options options = new Options();
        options.setCreateIfMissing(true);
        rocksDB = RocksDB.open(options, XiehuaConfig.getInstance().get(PERSISTENCE_PATH));
        rocksDB.put(key.getBytes(), value.getBytes());
        rocksDB.close();
    }

    public String get(String key) throws RocksDBException {
        Options options = new Options();
        options.setCreateIfMissing(true);
        rocksDB = RocksDB.open(options, XiehuaConfig.getInstance().get(PERSISTENCE_PATH));
        byte[] value = rocksDB.get(key.getBytes());
        rocksDB.close();
        return new String(value);
    }

    public Map<byte[], byte[]> get(List<String> keys) throws RocksDBException {
        Options options = new Options();
        options.setCreateIfMissing(true);
        rocksDB = RocksDB.open(options, XiehuaConfig.getInstance().get(PERSISTENCE_PATH));
        Map<byte[], byte[]> valueMap = rocksDB.multiGet(keys.stream().map(s -> s.getBytes()).collect(Collectors.toList()));
        rocksDB.close();
        return valueMap;
    }

    public List<byte[]> getAll() throws RocksDBException {
        Options options = new Options();
        options.setCreateIfMissing(true);
        return RocksDB.listColumnFamilies(options, XiehuaConfig.getInstance().get(PERSISTENCE_PATH));
    }

    public void delete(String key) throws RocksDBException {
        Options options = new Options();
        options.setCreateIfMissing(true);
        rocksDB = RocksDB.open(options, XiehuaConfig.getInstance().get(PERSISTENCE_PATH));
        rocksDB.delete(key.getBytes());
        rocksDB.close();
    }

    public static void main(String[] args) throws Exception {
        RocksPersitence persitence = new RocksPersitence();
        DelayJob job = new DelayJob("test","hello",12L);
        String taskId = UUID.randomUUID().toString();
        job.setJobId(taskId);
        persitence.persistence(job);
        System.out.println(persitence.queryJob(taskId));
        persitence.close();
    }


}
